<script setup lang="ts">
import UserAvatar from "@/components/common/UserAvatar.vue";
import * as SystemApis from "@/api/system";
import {onMounted, ref, nextTick } from "vue";
import * as SystemTypes from "@/api/system/types";
import {useLoginStore} from "@/store/login";
import {isEmptyString} from "@/utils/string";
import {ElMessage} from "element-plus";
import {formatDate} from "@/utils/time";

const props = defineProps(['sessionId', 'toUserId'])
const emit = defineEmits(['onClose']);
const loginStore = useLoginStore();
const sysMessageSessionChat = ref<SystemTypes.SysMessageSessionChatResp>()
const chatContainerRef = ref(null)
const messageInput = ref('')
const messagePosting = ref(false)
const showSessionChatDialog = ref(false)
const loadMessageSessionChat = () => {
  if (props.sessionId) {
    SystemApis.querySysMessageSessionChat(props.sessionId).then(result => {
      sysMessageSessionChat.value = result
      showSessionChatDialog.value = true
      scrollToChatBottom()
    })
  } else if (props.toUserId) {
    if (props.toUserId == loginStore.userId) {
      ElMessage.error("您无法给自己发送私信哦！")
      emit('onClose')
      return
    }
    SystemApis.querySysMessageSessionChatByToUser(props.toUserId).then(result => {
      sysMessageSessionChat.value = result
      showSessionChatDialog.value = true
      scrollToChatBottom()
    })
  }

}
// 实现对话时保持滚动在底部
const scrollToChatBottom = async () => {
  await nextTick();
  const container = chatContainerRef.value;
  // 滚动到最底部
  setTimeout(() => {
    container.scrollTo({
      top: container.scrollHeight,
      behavior: 'smooth'
    });
  }, 100);
}
const handleMessageInputKeyDown = (event: KeyboardEvent) => {
  if (event.key == 'Enter') {
    handlePostMessage()
    event.preventDefault()
  }
}
const handlePostMessage = () => {
  if (isEmptyString(messageInput.value)) {
    messageInput.value = ''
    ElMessage.warning("消息内容不能为空")
    return
  }
  messagePosting.value = true
  let req: SystemTypes.SysMessagePostReq = {
    sessionId: sysMessageSessionChat.value.sessionId,
    content: messageInput.value
  }
  SystemApis.postMessage(req).then(() => {
    const message: SystemTypes.SysMessageResp = {
      messageContent: messageInput.value,
      messageTime: formatDate(new Date(), '{y}-{m}-{d} {h}:{i}'),
      self: true
    }
    sysMessageSessionChat.value.messageList.push(message)
    scrollToChatBottom()
  }).finally(() => {
    messagePosting.value = false
    messageInput.value = ''
  })
}

onMounted(()=>{
  loadMessageSessionChat()
})
</script>

<template>
  <el-dialog v-model="showSessionChatDialog" :title="sysMessageSessionChat?.toUser.userName" center width="80%"
             style="max-width:720px; min-width: 300px; height: 600px;border-radius: 0.5rem" @close="emit('onClose')">
    <div class="h-[530px]">
      <ul class="py-6 px-6 h-2/3 border-b overflow-auto" ref="chatContainerRef">
        <li v-for="chatMessage in sysMessageSessionChat.messageList">
          <div v-if="chatMessage.self" class="flex flex-row justify-end mb-4">
            <div class="flex flex-row shrink">
              <div class="chat-message-content py-3 px-4 rounded-lg break-all">{{ chatMessage.messageContent }}</div>
              <div class="mr-3 horn-right shrink-0"></div>
            </div>
            <UserAvatar :size="40" :file-id="loginStore.avatar" class="shrink-0"></UserAvatar>
          </div>
          <div v-else class="flex flex-row justify-start mb-4">
            <UserAvatar :size="40" :file-id="sysMessageSessionChat.toUser.userAvatar" class="mr-3 shrink-0"></UserAvatar>
            <div class="flex flex-row shrink">
              <div class="horn-left shrink-0"></div>
              <div class="chat-message-content py-3 px-4 rounded-lg break-all">{{ chatMessage.messageContent }}</div>
            </div>
          </div>
        </li>
      </ul>
      <div class="py-3">
        <el-input
            size="large"
            v-model="messageInput"
            maxlength="200"
            style="width: 100%;"
            placeholder=""
            show-word-limit
            type="textarea"
            :rows="4"
            resize="none"
            class="mb-3 message-input"
            @keydown="handleMessageInputKeyDown"></el-input>
        <div class="text-right"><span class="text-gray-500 mr-3">按Enter键发送</span>
          <el-button type="primary" @click="handlePostMessage()" :disabled="messageInput == ''" :loading="messagePosting">发送</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<style scoped>
.chat-message-content {
  background: #f3f3f3;
}

.horn-right {
  width: 8px;
  height: 30px;
  background: #f3f3f3;
  clip-path: polygon(
      0px 12px,
      8px 18px,
      0px 24px
  )
}

.horn-left {
  width: 8px;
  height: 30px;
  background: #f3f3f3;
  clip-path: polygon(
      8px 12px,
      8px 24px,
      0px 18px
  )
}

.menu-ul li.selected div:before {
  background-color: var(--el-color-primary);
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 3px;
}

.message-input >>> .el-textarea__inner {
  box-shadow: none;
}
.message-input >>> .el-textarea__inner:hover {
  box-shadow: none;
}
.message-input >>> .el-textarea__inner:focus {
  box-shadow: none;
}
</style>